<?php

namespace App\Http\Controllers\Admin;
use App\Admin\Admin;
use App\Admin\Arole;
use App\Admin\GetCategory;
use App\Admin\Role;
use App\Admin\Rule;
use Validator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;

class UserController extends Controller
{
    //get Admin/user 全部用户列表
    public function index(Request $request)
    {
        $user = Admin::select(DB::Raw('admin.*,GROUP_CONCAT(role.display_name) as dname'))
            ->leftJoin('arole', 'arole.user_id','admin.id')
            ->leftJoin('role', 'role.id', 'arole.role_id')
            ->groupBy('admin.id')
            ->get();
        $count = count($user);
        //2、设置每页显示条数
        $rev = '4';
        //3、求总页数
        $sums = ceil($count/$rev);
        //4、求当前页
        $page = Input::get('page');
//        return $page;
        if(empty($page)){
            $page = "1";
        }
        $page = $page>0?$page:1;
        $page = $page<$sums?$page:$sums;
        //5、设置上一页、下一页
        $prev = ($page-1)>0?$page-1:1;
        $next = ($page+1)<$sums?$page+1:$sums;
        //6、求偏移量
        $offset = ($page-1)*$rev;
        $user = Admin::select(DB::Raw('admin.*,GROUP_CONCAT(role.display_name) as dname'))
            ->leftJoin('arole', 'arole.user_id','admin.id')
            ->leftJoin('role', 'role.id', 'arole.role_id')
            ->groupBy('admin.id')
            ->offset($offset)
            ->limit($rev)
            ->get();
        if($user==[]){
            $page = ($page-1)>0?$page-1:1;
        }
        return view('admin.user.userlist',compact('user','count','page','sums'));
    }
    public function changeOrder(Request $request)
    {
        $input = $request->all();
        $user = Admin::find($input['id']);
        $user->order = $input['order'];
        $res = $user->save();
        if($res){
            $data = ['status'=>0,
                'msg'=>'用户排序更新成功',

            ];
        }else{
            $data = [
                'status'=>1,
                'msg'=>'用户排序更新失败，请重试',
            ];
        }
        return $data;
    }
    public function changeSta(Request $request)
    {
        $input = $request->all();
        $user = Admin::find($input['id']);
        $user->status=($user->status==1?0:1);
        $res = $user->save();
        if($res){
            $data = ['status'=>0,
                'msg'=>'登陆权限更新成功',

            ];
        }else{
            $data = [
                'status'=>1,
                'msg'=>'登陆权限更新失败，请重试',
            ];
        }
        return $data;
    }
//
    public function chanf(Request $request)
    {

    }
    public function show(Request $request)
    {

        $user = Admin::select(DB::Raw('admin.*,GROUP_CONCAT(role.display_name) as dname'))
            ->leftJoin('arole', 'arole.user_id','admin.id')
            ->leftJoin('role', 'role.id', 'arole.role_id')
            ->where('username','like','%'.$request->data.'%')
            ->groupBy('admin.id')
            ->get();
        //1、查询数据库总条数
        $count = count($user);
        //2、设置每页显示条数
        $rev = '4';
        //3、求总页数
        $sums = ceil($count/$rev);
        //4、求当前页
        $page = Input::get('page');
//        return $page;
        if(empty($page)){
            $page = "1";
        }
        $page = $page>0?$page:1;
        $page = $page<$sums?$page:$sums;
        //5、设置上一页、下一页
        $prev = ($page-1)>0?$page-1:1;
        $next = ($page+1)<$sums?$page+1:$sums;
        //6、求偏移量
        $offset = ($page-1)*$rev;
        $user = Admin::select(DB::Raw('admin.*,GROUP_CONCAT(role.display_name) as dname'))
            ->leftJoin('arole', 'arole.user_id','admin.id')
            ->leftJoin('role', 'role.id', 'arole.role_id')
            ->where('username','like','%'.$request->data.'%')
            ->groupBy('admin.id')
            ->offset($offset)
            ->limit($rev)
            ->get()->toArray();
//        return $request->data;
        if($request->isMethod('post')) {
            $data='';
            if(!empty($user)){
                foreach($user as $u) {
                    if ($u['status'] == 1) {
                        $str = "<td style='text-align:center;line-height:50px'><button class='btn btn-primary' id='btn" . $u['id'] . "' onclick='changesta(this," . $u['id'] . ")'>开启</button></td>";
                    } else {
                        $str = "<td style='text-align:center;line-height:50px'><button class='btn btn-primary' id='btn" . $u['id'] . "' onclick='changesta(this," . $u['id'] . ")'>开启</button></td>";
                    }
                    $data .=
                        "<tr><td style='line-height:50px'><input type='text' name='ord[]' value='"
                        . $u['order'] .
                        "'style='width:40px;text-align:center;line-height:50px;margin-bottom:0px' ></td><td style='text-align:center;line-height:50px'>"
                        . $u['id'] .
                        "</td><td style='text-align:center;line-height:50px'>"
                        . $u['username'] .
                        "$str" .
                        " <td style='text-align:center;line-height:50px'>" . $u['dname'] . "</td>" .
                        "<td style='text-align:center;line-height:50px'>
                    <button type='button' class='btn btn-success'>" .
                        "<a href=\"user/".$u['id']."/edit?page=".$page."\" style=\"color:white\">修改</a></button> ".
                        "<button type=\"button\" class='btn btn-danger'>
                    <a href=\"javascript:\" onclick=\"delArt(".$u['id'].")\" style=\"color:white\">删除</a>
                    </button>
                    "."<button type='button' class='btn btn-danger'>
                    <a href=\"riddle/".$u['id'].'?page='.$page."\" style='color:white'>添加角色</a>
                    </button>" .
                        "</td>" .
                        "</tr>";
                }
                    $a = "<a href='javascript:void(0)' onclick='page(1)'>首页</a><a href='javascript:void(0)' onclick='page(" . $prev . ")'>上一页</a><a href='javascript:void(0)' onclick='page(" . $next . ")'>下一页</a><a href='javascript:void(0)' onclick='page(" . $sums . ")'>尾页</a>";
                    $arr = [
                        'data' => $data,
                        'page' => $a,
                        'count' => $count,
                        'ever' => $page,
                        'all' => $sums,
                        'msg' => '1',
                    ];
                    $json = json_encode($arr, JSON_UNESCAPED_UNICODE);
                    return $json;
                }else{
                $data= "<th scope='col' style='text-align: center' colspan='7'>暂无用户</th>";
                $arr=['data'=>$data,'msg'=>0];
                $json = json_encode($arr,JSON_UNESCAPED_UNICODE);
                return $json;
            }
        }
        $data='';
        if(!empty($user)) {
            foreach($user as $u) {
                if($u['status']==1){
                    $str = "<td style='text-align:center;line-height:50px'><button class='btn btn-primary' id='btn".$u['id']."' onclick='changesta(this,".$u['id'].")'>开启</button></td>";
                }else{
                    $str = "<td style='text-align:center;line-height:50px'><button class='btn btn-primary' id='btn".$u['id']."' onclick='changesta(this,".$u['id'].")'>开启</button></td>";
                }
                $data .=
                    "<tr><td style='line-height:50px'><input type='text' name='ord[]' value='"
                    . $u['order'] .
                    "'style='width:40px;text-align:center;line-height:50px;margin-bottom:0px' onchange='changeOrder(this,".$u['id'].")' ></td><td style='text-align:center;line-height:50px'>"
                    . $u['id'] .
                    "</td><td style='text-align:center;line-height:50px'>"
                    . $u['username'] .
                    "$str".
                    " <td style='text-align:center;line-height:50px'>".$u['dname']."</td>".
                    "<td style='text-align:center;line-height:50px'>
                    <button type='button' class='btn btn-success'>".
                    "<a href=\"user/".$u['id']."/edit?page=".$page."\" style=\"color:white\">修改</a></button> ".
                    "<button type=\"button\" class='btn btn-danger'>
                    <a href=\"javascript:\" onclick=\"delArt(".$u['id'].")\" style=\"color:white\">删除</a>
                    </button>
                    "."<button type='button' class='btn btn-danger'>
                    <a href=\"riddle/".$u['id'].'?page='.$page."\" style='color:white'>添加角色</a>
                    </button>".
                    "</td>".
                   "</tr>";

            }
                $a = "<a href='javascript:void(0)' onclick='page(1)'>首页</a><a href='javascript:void(0)' onclick='page(" . $prev . ")'>上一页</a><a href='javascript:void(0)' onclick='page(" . $next . ")'>下一页</a><a href='javascript:void(0)' onclick='page(" . $sums . ")'>尾页</a>";
                $arr = [
                    'data' => $data,
                    'page' => $a,
                    'count' => $count,
                    'ever' => $page,
                    'all' => $sums,
                    'msg' => '1',
                ];
                $json = json_encode($arr, JSON_UNESCAPED_UNICODE);
                return $json;

        }else{
            $data= "<th scope='col' style='text-align: center' colspan='7'>暂无用户</th>";
            $a = "<a href='javascript:void(0)' onclick='page(1)'>首页</a><a href='javascript:void(0)' onclick='page(1)'>上一页</a><a href='javascript:void(0)' onclick='page(1)'>下一页</a><a href='javascript:void(0)' onclick='page(1)'>尾页</a>";
            $arr=[
                'data'=>$data,
                'count'=>$count,
                'page'=>$a,

            ];
            $json = json_encode($arr,JSON_UNESCAPED_UNICODE);
            return $json;
        }

    }
    //get Admin/user/create 添加用户信息
    public function create()
    {
        return view('admin/user/useradd');
    }
//用户添加
    public function changeadd(Request $request)
    {
        $input = Input::except('_token', 'password_confirmation');
        $password = $input['password'];
        $password = md5($password);
        $input['password']=$password;
        $rules = [
            'username'=>'required',
            'password'=>'required'
        ];
        $message = [
            'username.required'=>'角色名不能为空!',
            'password.required'=>'密码不能为空'
        ];
        $this->validate($request,$rules,$message);
        $res = Admin::create($input);
        if($res){
            $data = ['status'=>0,
                'msg'=>'用户添加成功',
            ];
        }else{
            $data = [
                'status'=>1,
                'msg'=>'用户添加失败，请重试',
            ];
        }
        return $data;

    }
    //post Admin/user 添加用户信息提交
    public function store(Request $request)
    {

    }
    //get Admin/user/{user}/edit   编辑用户信息
    public function edit($user_id)
    {
        $page = $_GET['page'];
        $user = Admin::find($user_id);
        return view('admin/user/useredit',compact('user','page'));

    }
    //put Admin/navs/{navs} 更新用户信息
    public function update($id)
    {
        $page = Input::get('page');
//        return $page;
        if(empty($page)){
            $page = "1";
        }
        $input = Input::except('_token','_method','page');
        $res = Admin::where('id',$id)->update($input);
        if($res){
            return redirect('admin/user?page='.$page);
        }else{
            return back()->with('errors','用户更新失败');
        }

    }

    //delete Admin/nav/{nav}  删除用户信息
    public function destroy($id)
    {
        $res = Admin::where('id',$id)->delete();
        if($res){
            Arole::where('user_id',$id)->delete();
            $data = [
                'status'=>0,
                'msg'=>'用户删除成功!',
            ];
        }else{
            $data = [
                'status'=>1,
                'msg'=>'用户删除失败!',
            ];
        }
        return $data;
    }

    public function cherg(Request $request)
    {
        $page = Input::get('page');
//        return $page;
        if(empty($page)){
            $page = "1";
        }
        if ($request->isMethod('post')) {
        $input = Input::except('_token');
       $role_id = $input['role_id'];
       $user_id = $input['id'];
        $arole = Arole::where('user_id',$user_id)->delete();
       $role=[];
       foreach($role_id as $v){
           $role[] = ['user_id'=>"$user_id",'role_id'=>"$v"];
       }
       $res = DB::table('arole')->insert($role);
       if($res){
            return redirect('admin/user?page='.$page);
       }else{
           return back();
       }
        }
        //查询所有的权限
        $id = $request->id;
        $user = Admin::where('id',$id)->select()->get();
        $username = $user[0]->username;
        $role_is = Arole::where('user_id',$id)->get()->toArray();
        $role_id=[];
        foreach($role_is as $r){
            $role_id[] = $r['role_id'];
        }
        $role = Role::all();
        $getCate = new GetCategory();
        $role = (object)$getCate->getTree($role);
//        $power = (object)getTree($power);
        return view('admin.user.rmiddle',compact('username','role','role_id','id','page'));
    }

}
